<?php

class Talktangle_Model_DbTable_Vidtangles extends Engine_Db_Table
{
    protected $_rowClass = 'Talktangle_Model_Vidtangle';
    
  /**
   * @const SET IMAGE WIDTH
   */
  const IMAGE_WIDTH = 720;
  /**
   * @const SET IMAGE HIGHT
   */
  const IMAGE_HEIGHT = 720;
  /**
   * @const SET THUMB IMAGE WIDTH
   */
  const THUMB_WIDTH = 140;
  /**
   * @const SET THUMB IMAGE HIGHT
   */
  const THUMB_HEIGHT = 160;
  
  public function cropPhoto($file,$name,$params){
     $imageInfo = @getimagesize($file);
     $width = $imageInfo[0];
     $height = $imageInfo[1];
     $offsetCount = Engine_Api::_()->getApi('ptangle','talktangle')->getNumberOffsetImage();
     
     $offsetWidth = $width/$offsetCount;
     $offsetHeight = $height/$offsetCount;
     $filename = APPLICATION_PATH.'/public/talktangle_vidtangle';
     if(!file_exists($filename)){
            mkdir($filename, 0777);
     }
     $filename .= '/offset'.time();
     if(!file_exists($filename)){
            mkdir($filename, 0777);
     }  
     
     $ext = ltrim(strrchr($name, '.'), '.');
     
     for ($i = 0; $i < $offsetCount ; $i++){
        for ($j = 0; $j < $offsetCount ; $j++){
          $image = Engine_Image::factory();
          $mainName = $filename.'/'.'image'.$i.$j.'.'.$ext;
          $image->open($file)
              ->crop($offsetWidth*$j, $offsetHeight*$i,$offsetWidth,$offsetHeight)
              ->write($mainName)
              ->destroy();
          $photoFile = Engine_Api::_()->storage()->create($mainName, $params);
          $photoFile->save();
          
        }  
     }
  }
  
  public function uploadPhoto($params,$file){
    if ($file instanceof Storage_Model_File) {
      $params['file_id'] = $file->getIdentity();
    } 
    else 
    {
      //Get image info and resize
      $name = basename($file['tmp_name']);
      $path = dirname($file['tmp_name']);
      $extension = ltrim(strrchr($file['name'], '.'), '.');

       
      $mainName = $path . '/m_' . $name . '.' . $extension;
      $thumbName = $path . '/t_' . $name . '.' . $extension;
      
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::IMAGE_WIDTH, self::IMAGE_HEIGHT)
              ->write($mainName)
              ->destroy();
     
        
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
              ->write($thumbName)
              ->destroy();
      
      $thumbW = $image->getWidth();
      $thumbH = $image->getHeight();
        
      //Store photos
      $photo_params = array(
          'parent_id'   =>   0,
          'parent_type' => 'talktangle_vidtangle'
      );
      
     
      
      $photoFile = Engine_Api::_()->storage()->create($mainName, $photo_params);
      $photoFile->save();
      
      $thumbFile = Engine_Api::_()->storage()->create($thumbName, $photo_params);
      $thumbFile->save();
      $photoFile->bridge($thumbFile, 'thumb.normal');
      
      //Storage full size image.
      if (Engine_Api::_()->getApi('settings', 'core')->getSetting('talktangle.photo.fullsize.storage', 0)) {
          $fullsizeName = $path . '/o_' . $name . '.' . $extension;
          $image = Engine_Image::factory();
          $image->open($file['tmp_name'])
                  //->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
                  ->write($fullsizeName)
                  ->destroy();
          $fullsizeFile = Engine_Api::_()->storage()->create($fullsizeName, $photo_params);
          $fullsizeFile->save();
          $photoFile->bridge($fullsizeFile, 'fullsize.normal');
          @unlink($fullsizeName);          
          //$fullsizeFile->width = $fullW;
          //$fullsizeFile->height = $fullH;
          
      }
      $params = array(
            'parent_type' => 'talktangle_vidtangle',
            'parent_id'   =>   $photoFile->getIdentity(), 
      );
      //$this->cropPhoto($file['tmp_name'],$file['name'],$params)  ;
      $link_file = Engine_Api::_()->getApi('storage', 'storage')->get($photoFile->file_id, 'thumb.normal');
      $this->cropPhoto($file['tmp_name'],$file['name'],$params)  ;
      //Remove temp files
      @unlink($mainName);
      @unlink($thumbName);
        
      return $photoFile;

      
    } 
  }
  
  public function getFFmpegPath(){
     return  Engine_Api::_()->getApi('settings', 'core')->getSetting('video.ffmpeg.path','D:\Developer\xampp\htdocs\clouds\trunk\application\soft\ffmpeg.exe');
  }
  public function getImageToLocation($src){
        $realPath =  APPLICATION_PATH.'/';
        
       
        // Make sure FFMPEG path is set
        $ffmpeg_path = $this->getFFmpegPath();
        if (!$ffmpeg_path) {
          $error_msg1 = 'Ffmpeg not configured';
          throw new Exception($error_msg1);
        }
        
        // Make sure FFMPEG can be run
        if (!@file_exists($ffmpeg_path) || !@is_executable($ffmpeg_path)) {
          $output = null;
          $return = null;
          exec($ffmpeg_path . ' -version', $output, $return);
          if ($return > 0) {
            $error_msg2 = 'Ffmpeg found, but is not executable';
            throw new Exception($error_msg2);
          }
        }
    
        // Check we can execute
        if (!function_exists('shell_exec')) {
          $error_msg3 = 'Unable to execute shell commands using shell_exec(); the function is disabled.';
          throw new Exception($error_msg3);
        }
    
        // Check the video temporary directory
        $tmpDir = $realPath  . 'temporary/video/';
        if (!is_dir($tmpDir)) {
          if (!mkdir($tmpDir, 0777, true)) {
            $error_msg4 = 'Video temporary directory did not exist and could not be created.';
            throw new Exception($error_msg4);
          }
        }
        if (!is_writable($tmpDir)) {
          $error_msg5 = 'Video temporary directory is not writable.';
          throw new Exception($error_msg5);
        }
    
        
        
        $originalPath = $src;
        
        $name = md5(basename($originalPath).time()).'.jpg';
        //where to save the image  
        $image = $realPath .'temporary/video/'.$name;  
          
        //time to take screenshot at  
        $interval = 15;  
          
        //screenshot size  
        $size = '720x720';  
        //ffmpeg command  
        
        
        $cmd = "$ffmpeg_path  -ss $interval  -i $originalPath -f image2 -t 1 -s $size $image 2>&1";
        try{
            exec($cmd);
        }
        catch(Exception $e){
            throw $e;
        }
    
        $ok = file_exists($image);
        $size = filesize($image);
        return array('tmp_name' =>$image,'ext'=>'jpg','name' => $name,'size' =>$size);
        
    }
    
    
}